package com.xbongbong.pay.platform.unionpay.utils;

import com.xbongbong.paas.toolbox.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 银联 签名生成
 * @author 魏荣杰
 * @date 2021/1/19 16:42
 * @since
 * @version
 */
public class UnionPaySignUtil {
    private static final Logger LOG = LoggerFactory.getLogger(UnionPaySignUtil.class);


    public static String createSign(Map<String, String> params, String encoding, PrivateKey privateKey) throws Exception {
        String signMethod = params.get("signMethod");
        if (StringUtil.isEmpty(signMethod)) {
            return null;
        }

        String sign = null;
        UnionPaySignTypeEnum signTypeEnum = UnionPaySignTypeEnum.getByCode(signMethod);
        if (Objects.nonNull(signTypeEnum)) {
            String urlString = getUrlString(params);
            LOG.error("=====urlString === " + urlString);
            switch (signTypeEnum) {
                case RSA:
                    byte[] bytes = UnionPaySecureUtil.sha256X16(urlString, encoding);
                    sign = UnionPaySecureUtil.base64Encode(UnionPaySecureUtil.signBySoft256(privateKey, bytes));
                    break;
//                case SHA256:
//                    String strBeforeSha256 = urlString + "&" +
//UnionPaySecureUtil.sha256X16Str(, encoding);
//                    sign = UnionPaySecureUtil.sha256X16Str(strBeforeSha256, encoding);
//                    break;
//                case SM3:
//                    String strBeforeSM3 = urlString + "&" + UnionPaySecureUtil.sm3X16Str(secureKey, encoding);
//                    break;
                default:
                    return null;
            }
        }
        return sign;
    }


    public static String getUrlString(Map<String, String> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (StringUtil.isNotEmpty(value)) {
                stringBuffer.append(key).append("=").append(value).append("&");
            }
        }
        return stringBuffer.substring(0, stringBuffer.length() - 1);
    }
}
